package ge.telasi.tasks.ui.user;

import ge.telasi.tasks.ui.UIUtils;
import ge.telasi.tasks.ui.comp.SuggestionText;
import ge.telasi.tasks.ui.log.LoggableField;
import ge.telasi.tasks.ui.log.Logger;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;

/**
 * @author dimitri
 */
public class ServerSelector extends JPanel implements LoggableField {
    private static final long serialVersionUID = 1143211272235736080L;

    private SuggestionText field;
    private ServerItem serverItem;

    public ServerSelector() {
        initComponents();
        reset();
    }

    private void initComponents() {
        setLayout(new BorderLayout(5, 5));
        field = new SuggestionText();
        field.setEditable(false);
        field.setSuggestion("აარჩიეთ სერვერი");
        add(field, BorderLayout.CENTER);
        JButton btn = new JButton("...");
        add(btn, BorderLayout.EAST);
        btn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ServerItemSelectorDialog dialog = new ServerItemSelectorDialog(ServerSelector.this);
                dialog.refresh();
                UIUtils.openDialog(dialog);
                if (dialog.getServerItem() != null) {
                    serverItem = dialog.getServerItem();
                    reset();
                }
            }
        });
        btn.setToolTipText("აარჩიეთ სხვა სერვერი");
    }

    private void reset() {
        if (serverItem == null) {
            field.setText("");
        } else {
            field.setText(serverItem.toString());
            field.setCaretPosition(0);
        }
        setException(null);
    }

    public ServerItem getServerItem() {
        return serverItem;
    }

    public void setServerItem(ServerItem serverItem) {
        this.serverItem = serverItem;
        reset();
    }

    public void setException(Exception ex) {
        field.setException(ex);
    }

    public Logger getLogger() {
        return field.getLogger();
    }

    public void setLogger(Logger logger) {
        field.setLogger(logger);
    }

}
